package com.yvan.periscope.controller;

import com.yvan.es.SearchAction;
import com.yvan.periscope.domain.HistogramTitleEnum;
import com.yvan.periscope.dto.request.SqlHistogramReq;
import com.yvan.periscope.dto.request.SqlSummaryReq;
import com.yvan.periscope.service.HistogramService;
import com.yvan.platform.JsonWapper;
import io.searchbox.client.JestClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者： lzw<br/>
 * 创建时间：2018-09-10 16:31 <br/>
 */
@Api(description = "SQL指标概况")
@RequestMapping("/analytics")
@RestController
@Slf4j
public class SqlSummaryController {

    private static final String PER_SQL_INDEX = "per-sqls-*";

    @Autowired
    private JestClient jestClient;

    @Autowired
    private HistogramService histogramService;

    @ApiOperation("汇总数据")
    @GetMapping("/sql_summary.json")
    public Object sqlSummary(HttpServletRequest request, HttpServletResponse response, SqlSummaryReq sqlSummaryReq) throws IOException {
        sqlSummaryReq.defaultParam();
        SearchAction action = new SearchAction(log);
        action.index = PER_SQL_INDEX;
        action.size = 0;
        action.query.filter.range("@timestamp", sqlSummaryReq.getMin().toString(), true, sqlSummaryReq.getMax().toString(), true);
        action.agg.sum("cost_sum");
        action.agg.sum("executeCount");
        action.agg.max("cost_max");
        action.agg.max("concurrentMax");
        action.agg.terms("sql")
                .sum("executeCount")
                .max("concurrentMax")
                .sum("cost_sum")
                .avg("cost_sum")
                .max("cost_max")
                .order("sum@sql@cost_sum", "desc");
        action.agg.maxBucket("group_by@sql@sql.sum@sql@executeCount", "maxOfexecuteCountSum");
        JsonWapper result = action.search(jestClient).getJsonWapper();
        List resultList = result.asList("aggregations", "group_by@sql@sql", "buckets").innerList;
        Object costMax = result.get("aggregations", "group_by@cost_max@cost_max");
        Object costSum = result.get("aggregations", "group_by@cost_sum@cost_sum");
        Object executeCount = result.get("aggregations", "group_by@executeCount@executeCount");
        Object concurrentMax = result.get("aggregations", "group_by@concurrentMax@concurrentMax");
        Object maxOfExecuteCountSum = result.get("aggregations", "group_by@maxOfexecuteCountSum@buckets");
        // summaryData 是汇总数据
        Map<String, Object> summaryData = new HashMap<>();
        summaryData.put("executeCount", executeCount);
        summaryData.put("costSum", costSum);
        summaryData.put("costMax", costMax);
        summaryData.put("concurrentMax", concurrentMax);
        // chartDate 是图表数据
        Map<String, Object> chartDate = new HashMap<>();
        chartDate.put("chartList", resultList);
        chartDate.put("maxOfCostMax", costMax);
        chartDate.put("maxOfexecuteCountSum", maxOfExecuteCountSum);
        // 汇总数据
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("chartDate", chartDate);
        resultMap.put("summaryData", summaryData);
        response.addHeader("Q", action.build().toString(false));
        return resultMap;
    }

    @ApiOperation("表格数据")
    @GetMapping("/sqls.json")
    public Object sqlData(HttpServletRequest request, HttpServletResponse response, SqlSummaryReq sqlSummaryReq) throws IOException {
        sqlSummaryReq.defaultParam();
        SearchAction action = new SearchAction(log);
        action.index = PER_SQL_INDEX;
        action.size = 0;
        action.query.filter.range("@timestamp", sqlSummaryReq.getMin().toString(), true, sqlSummaryReq.getMax().toString(), true);
        action.agg.terms("sql")
                .sum("executeCount")
                .max("concurrentMax")
                .sum("cost_sum")
                .max("cost_max")
                .order("sum@sql@cost_sum", "desc");
        JsonWapper result = action.search(jestClient).getJsonWapper();
        response.addHeader("Q", action.build().toString(false));
        return result;
    }

    @ApiOperation("直方图数据")
    @GetMapping("/sql_histogram.json")
    public Object sqlHistogram(HttpServletRequest request, HttpServletResponse response, @Validated SqlHistogramReq sqlHistogramReq) throws IOException {
        sqlHistogramReq.defaultParam();
        HistogramTitleEnum histogramTitleEnum = HistogramTitleEnum.getEnum("sql", sqlHistogramReq.getHistogramPrefix());
        if (histogramTitleEnum == null) {
            return null;
        }
        return histogramService.findHistogramFromPeriscope(
                PER_SQL_INDEX,
                sqlHistogramReq.getHistogramPrefix(),
                histogramTitleEnum.getPartition(),
                sqlHistogramReq.getMin(),
                sqlHistogramReq.getMax(),
                histogramTitleEnum.getXAxisTitle(),
                histogramTitleEnum.getYAxisTitle()
        );
    }
}
